package tank

import (
	"code.sohuno.com/golang/scs-go-sdk/scs"
	"code.sohuno.com/golang/scs-go-sdk/sohucs"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"mime/multipart"
	"os"
)

func uploadFiles(c *gin.Context, uploadDir string, fileNames []string, files ...*multipart.FileHeader) error {
	for i, f := range files {
		var actualFilename string
		if fileNames != nil {
			actualFilename = fileNames[i]
		} else {
			actualFilename = f.Filename
		}
		if err := c.SaveUploadedFile(f, uploadDir+actualFilename); err != nil {
			log.Println(err.Error())
			return err
		}
	}
	return nil
}

func createUploadDirIfNotExists(uploadDir string) {
	if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
		os.MkdirAll(uploadDir, os.ModePerm)
	}
}

type S3 struct {
	AccessKey string
	SecretKey string
	Bucket    string
	Directory string
	S3Host    string
}

var s3 S3
var s3Client *scs.SCS

func genFilePath(uid string, suffix string) string {
	return s3.Directory + "/" + uid + "/" + suffix
}

func uploadFiles2S3(uid string, suffix []string, files ...*multipart.FileHeader) error {
	b := s3Client.Bucket(s3.Bucket)
	for i, f := range files {
		file, err := f.Open()
		if err != nil {
			return err
		}
		filePath := genFilePath(uid, suffix[i])
		if err = b.PutReader(filePath, file, f.Size, f.Header.Get("Content-Type")); err != nil {
			return err
		}
	}
	return nil
}

func getS3FilePath(uid string, suffix string) string {
	filePath := genFilePath(uid, suffix)
	return fmt.Sprintf("https://%s/%s", s3.S3Host, filePath)
}

const (
	AccessKy  = "C5O300AwAjlYIkAdqaVaKA=="
	SecretKey = "jrcrUNQIG70ShgSoNH5I7g=="
	Bucket    = "sohu1024"
	Directory = "code"
	S3Host    = "sohu1024.bjcnc.scs.sohucs.com"
)

func init() {
	s3 = S3{
		AccessKey: AccessKy,
		SecretKey: SecretKey,
		Bucket:    Bucket,
		Directory: Directory,
		S3Host:    S3Host,
	}
	auth := sohucs.Auth{AccessKey: s3.AccessKey, SecretKey: s3.SecretKey}
	s3Client = scs.New(auth, sohucs.BJCNC_IN)
}
